import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux'
import _ from 'lodash'

import { Table, Icon, Tag, Form, Select, Button, message, Modal, Input, Row, Col} from 'antd';
const Option = Select.Option,
    FormItem = Form.Item;
import {
  changePage,
  _validate,
  fetchSpecialists,
  special_operate,
  fetchData,
  API_URL,
  PORTRAIT,
  randomCode,
  formItemLayout,
  fetchAttachByEntry
} from '../../store/actions';
import SearchInput from '../../components/search-input'

class _SpecialistList extends React.Component{
    constructor(props){
        super(props);
        this.state ={
            filters:{},
            modality:[],
            specialists:[],
            detailVisible:false,
            detail:{},
            target:{}
        };
        this.onSelectChange = this.onSelectChange.bind(this);
    }
    static contextTypes = {
        router: React.PropTypes.object
    };
    fetchSpe(){
        const _this = this,
          token = _this.props.user.accessToken,
          opts = {accessToken:token};
            _this.props.dispatch(fetchSpecialists(opts,function(res1){
                const needData = _.filter(res1.content.data,_o =>{
                    return _o.ispass !=1 && _o.specialstatus != 0
                });
                if(_this.state.modality.length < 1){
                    const args = {
                        URL:'basedata/modality',
                        IsEnabled:true,
                        IsAuth:true,
                        opts:{accessToken:token},
                        Succ: function(res){
                            _this.setState({
                                specialists:needData,
                                modality:res.content
                            })
                        }
                    };
                    _this.props.dispatch(fetchData(args))
                }else{
                    _this.setState({
                        specialists:needData
                    })
                }
            }))
    }
    componentWillMount(){
        this.fetchSpe();
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            images: nextProp.items,
            isFetch:nextProp.isFetch,
            imagesLen:nextProp.items && nextProp.items.length
        })
    }
    onSelectChange(selectedRowKeys) {
        //this.setState({ selectedRowKeys });
    }
    _detail(e){
        e.preventDefault();
        const _t = e.target.dataset,
            _this = this,
            id = _t.id,
            target = _.filter(_this.state.specialists,_o => {
                return _o.account_id == id
                })[0],
            spe_id = target.specialist_id,
            colProps = {
                xs:24,
                sm:24,
                md:12,
                lg:12
            },
            modalities = (()=>{
              const _m = target.modalities,
                __m= this.state.modality;
              if(_m &&_m.length > 0){
                  return _.map(_m,(m,i)=>{
                      if(i<(_m.length-1)){
                          return <span key={__m[m].id}>{__m[m].code}，</span>
                      }else{
                          return <span key={__m[m].id}>{__m[m].code}</span>
                      }
                  })
              }else{
                  return false
              }
          })();
        function activeDetail(attach){
            let portrait = (<img style={{
                            height:'128px',
                            display:'block'}} src={`../../im-sdk/images/default.png`} />),
              certificate = [],
              token = _this.props.user.accessToken;
            if(attach){
                _.forEach(attach,o=>{
                    if(o.type == 'portrait'){
                        portrait = (<img style={{
                            height:'128px',
                            display:'block'}} src={`${API_URL}attachment/${o.id}?accessToken=${token}`} />)
                    }else if(o.type == 'certificate'){
                        certificate.push(<img style={{maxWidth:'100%'}} src={`${API_URL}attachment/${o.id}?accessToken=${token}`} />)
                    }
                });
            }
            const detail = (
              <Row>
                  <Col {...colProps}>
                      {portrait}
                      <ul className="label-list label-list-short">
                          <li><label>用户名</label>{target.username || '--'}</li>
                          <li><label>手机号</label>{target.mobile || '--'}</li>
                          <li><label>身份证号</label>{target.idcard || '--'}</li>
                          <li><label>姓名</label>{target.name || '--'}</li>
                          <li><label>性别</label>{target.gender == "F"?"女":(target.gender == "M"?"男":'--')}</li>
                          <li><label>职称</label>{target.title || '--'}</li>
                          <li><label>科室</label>{target.department || '--'}</li>
                          <li><label>医院</label>{target.hospital || '--'}</li>
                          <li><label>阅片类型</label>{modalities || '--'}</li>
                          <li><label>简介</label>{target.brief_introduction || '--'}</li>
                          <li><label>擅长领域</label>{target.domain || '--'}</li>
                          {target.ispass == 2?<li><label>拒绝理由</label>{target.remarks || '--'}</li>:''}
                      </ul>
                  </Col>
                  <Col {...colProps}>

                      <h2>资质附件</h2>
                      <div style={{
                        height:'460px',
                        overflow:'auto'
                      }}>
                          {certificate.length>0?certificate:<div style={{textAlign:'center',padding:'30px'}}>没有上传任何附件</div>}
                      </div>

                  </Col>
              </Row>
            );
            _this.setState({
                detailVisible:true,
                detail:detail,
                target:target
            })
        }
        _this.props.dispatch(fetchAttachByEntry({id:spe_id},function(res){
            console.log('成功',res)
            activeDetail(res.content)
        },function(res){
            activeDetail(false)
            console.log('失败',res)
        }))
    }
    passHandler(e){
        const _this = this;
        _validate(e,_this,function(data){
            let _data = Object.assign({},{account_id:_this.state.target.account_id,ispass:1},data);
            let _s = _.clone(_this.state.specialists);
            const _i = _.indexOf(_s,_this.state.target);
            let __s = _.pull(_s,_this.state.target);
            _this.setState({
                specialists:_s
            });
            _this.props.dispatch(special_operate('examine',{},_data,function(res){
                message.success('审核通过',1);
                _this.cancelHandler();
                 let _s = _.clone(_this.state.specialists);
                 _.pull(_s,_this.state.target);
                 _this.setState({
                     specialists:_s,
                     target: null
                 });
            },function(){
                message.error('业务处理失败',1)
            },function(){
                message.error('请求失败',1)
            }))
        })
    }
    cancelHandler(){
        this.props.form.resetFields()
        this.setState({
            detailVisible:false,
            detail:'暂无专家信息'
        })
    }
    /*returnHandler(){
        const _this = this;
        let _data = Object.assign({},{account_id:_this.state.target.account_id,ispass:0});
        _this.props.dispatch(special_operate('examine',{},_data,function(res){
            message.success('还原',1);
            let _s = _.clone(_this.state.specialists),
              __s =  _.clone(_this.state.target),
              _i = _.findIndex(_s,{account_id:__s.account_id});
            __s.ispass = 0;
            _s[_i] = __s;
            _this.setState({
                specialists:_s
            },function(){
                _this.cancelHandler();
                consloe.log(this.state.specialists)
            });

        },function(){
            message.error('业务处理失败',1)
        },function(){
            message.error('请求失败',1)
        }))
    }*/
    refuseHandler(e){
        const _this = this;
        _validate(e,_this,function(data){
            let _data = Object.assign({},{account_id:_this.state.target.account_id,ispass:2},data);
            _this.props.dispatch(special_operate('examine',{},_data,function(res){
                message.success('已拒绝',1);
                let _s = _.clone(_this.state.specialists),
                  __s =  _.clone(_this.state.target),
                  _i = _.findIndex(_s,{account_id:__s.account_id});
                __s.ispass = 2;
                __s.remarks = data.remarks;
                _s[_i] = __s;
                _this.setState({
                    specialists:_s
                },function(){
                    _this.cancelHandler();
                    consloe.log(this.state.specialists)
                });

            },function(){
                message.error('业务处理失败',1)
            },function(){
                message.error('请求失败',1)
            }))
        })

    }
    goEdit(e){
        e.preventDefault();
        const _t = e.target.dataset;
        this.props.dispatch(changePage('specialist-edit'));
        this.context.router.push({pathname:`/specialist-edit/${_t.id}`})
    }
    goDetail(e){
        e.preventDefault();
        const _t = e.target.dataset;
        //this.props.dispatch(changePage('specialist-detail'));
        this.context.router.push({pathname:`/specialist-detail/${_t.id}`})
    }
    addSpecialist(e){
        e.preventDefault();
        this.context.router.push({pathname:`/specialist-add`});
        this.props.dispatch(changePage('specialist-add'));
    }
    render(){
        const _this = this,
          modalities = _this.state.modality;
        const columns = [{
            title: '专家',
            dataIndex: 'name',
            width:100
        }, {
            title: '性别',
            dataIndex: 'gender',
            width:50,
            className: 'ant-column-status',
            render(text){
                return text === 'M' ? '男' : '女'
            }
        }, {
            title: '阅片类型',
            render(t,record){
                const _act = _.filter(modalities,a => {
                        return _.indexOf(record.modalities,a.id) !== -1
                    }),
                    _names =  (
                        _.map(_act,(_a,i) => {
                            if(i !== 0){
                                return `， ${_a.code}`;
                            }else{
                                return `${_a.code}`;
                            }
                        })
                    );
                return _names
            }
        }, {
            title: '擅长',
            width:200,
            dataIndex: 'domain',
            render(text,record){
                let _temp ='';
                if(text) {
                    if(text.length > 50)
                        _temp = text.substring(0, 50) + '...';
                    else
                        _temp = text;
                }
                return _temp;
            }
        }, {
            title: '状态',
            dataIndex: 'ispass',
            width:100,
            className: 'ant-column-status',
            render(text){
                switch (text){
                    case 0:
                        return <span style={{color:'red'}}>待审核</span>;
                    case 2:
                        return <span>拒绝</span>;
                    default:
                        return <span style={{color:'#ccc'}}>未知状态</span>
                }
            }
        }, {
            title: '操作',
            width:100,
            className: 'ant-column-operation',
            render: (text, record) => {
                switch(record.ispass){
                    case 0:
                        //待审核
                        return (
                            <div>
                                <a href="#" data-id={`${record.account_id}`} onClick={this._detail.bind(this)}>审核</a>
                            </div>
                        );
                    case 2:
                      //被拒绝
                        return (
                            <div>
                                <a href="#" data-id={`${record.account_id}`} onClick={this._detail.bind(this)}>查看</a>
                            </div>
                        );
                    default:
                        return (
                          <div>
                              <a href="#" data-id={`${record.account_id}`} onClick={this._detail.bind(this)}>查看</a>
                          </div>
                        );
                }
            }
        }];
        const dataLen = this.state.imagesLen;
        const pagination = {
            total: dataLen,
            showSizeChanger: true,
            onShowSizeChange(current, pageSize) {
                /*console.log('Current: ', current, '; PageSize: ', pageSize);*/
            },
            onChange(current) {
                /*console.log('Current: ', current);*/
            }
        };
        //const { loading, selectedRowKeys } = this.state;
        const rowSelection = {
            /*onChange(selectedRowKeys, selectedRows) {
             console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
             },
             onSelect(record, selected, selectedRows) {
             console.log(record, selected, selectedRows);
             },
             onSelectAll(selected, selectedRows, changeRows) {
             console.log(selected, selectedRows, changeRows);
             }*/
        };
        const layout = {
            labelCol: {
                span:4
            },
            wrapperCol: {
                span:20
            }
        }
        const { getFieldProps } = this.props.form,
          remarksProps = getFieldProps('remarks', {
            rules: [
                { required: true, message: '请输入审核理由'}
            ]
        }),modalProps = {
            title:"专家审核",
            onCancel:this.cancelHandler.bind(this),
            footer:(<div>

                {this.state.target.ispass != 0?'':(
                  <Form horizontal>
                      <FormItem {...layout} label="审核理由">
                          <Input {...remarksProps} type="textarea" placeholder="请输入审核理由"/>
                      </FormItem>
                  </Form>
                )}

                <Button onClick={this.cancelHandler.bind(this)}>取消</Button>
                {this.state.target.ispass == 0?<Button onClick={this.refuseHandler.bind(this)}>拒绝</Button>:''}
                {this.state.target.ispass == 0?<Button type="primary" onClick={this.passHandler.bind(this)}>审核通过</Button>:''}

            </div>),
            width:'70%'
        };
        return (
            <div id="images">
                <div style={{overflow: 'hidden', padding: '10px 0'}}>
                    <div style={{float:'left'}}>
                        <Button type="primary" size="large" icon="reload" onClick={this.fetchSpe.bind(this)}>获取最新数据</Button>
                    </div>
                    <div style={{float:'right'}}>
                        <SearchInput style={{ width: 200 }} placeholder='请输入关键字查询' />
                    </div>
                </div>
                <Table bordered rowSelection={rowSelection} columns={columns} dataSource={this.state.specialists} pagination={pagination} />
                <Modal
                  visible={this.state.detailVisible}
                  {...modalProps}
                >
                    {this.state.detail}
                </Modal>
            </div>
        )
    }
}
_SpecialistList = Form.create()(_SpecialistList);
let SpecialistList ;
export default SpecialistList = connect((state)=>{
    const {user} = state.rootReducer;
    return {user}
})(_SpecialistList)